# main.py
from email.policy import default
from typing import Optional
from fastapi import FastAPI, Request, Depends,  Query,Header, HTTPException
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from src import Config, logger_cust, global_data, LoginManager, dependencies, login_manager
from src.services.login import login,permission
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from src import Base, SessionLocal, get_db, engine, SysMangers
from sqlalchemy.orm import Session
from src.schemas.login_manager import AuthManager
from src.schemas import request_model
from src.middleware.strip_trailing_slash import StripTrailingSlashMiddleware
from src.middleware.cors_config import cors_config
from src import sysMangesRouter,sysDictsRouter,sysObjectsRouter
from src.services.manages import objects as serverObjects,dicts as serverDicts
# 文件读取
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
import mimetypes, os



# app = FastAPI()
app = FastAPI(
    docs_url="/docs",     # Swagger UI
    redoc_url="/redoc",   # ReDoc
)

# 注册中间件
app.add_middleware(StripTrailingSlashMiddleware)
app.add_middleware(CORSMiddleware, **cors_config)

# 1. 直接访问：http://127.0.0.1:8000/static/logo.png
app.mount("/public", StaticFiles(directory="static/public"), name="static")

"""
@app.middleware("http")
async def unify_slash(request: Request, call_next):
    if not request.url.path.endswith("/"):
        new_url = str(request.url).rstrip("/") + "/"
        return RedirectResponse(url=new_url, status_code=307)
    return await call_next(request)
"""


# 定义一个依赖项列表
# dependencies = [Depends(dependencies.auth_api_key), Depends(dependencies.auth_token)]
# dependencies = [Depends(dependencies.auth_api_key)]
# dependencies_api_key = [Depends(dependencies.auth_api_key)]

@app.on_event("startup")
async def startup_event():
    # 创建数据库表
    Base.metadata.create_all(bind=engine)
    #  初始化系统管理
    SysMangers.init_project(db=next(get_db()))
    # 初始化全局资源，例如数据库连接、配置加载等
    # 示例：await database.connect()


@app.on_event("shutdown")
async def shutdown_event():
    print("Main application is shutting down")
    # 清理全局资源，例如关闭数据库连接等
    # 示例：await database.disconnect()


app.include_router(sysMangesRouter, prefix="", tags=["System Manges API"], include_in_schema=True)
app.include_router(sysDictsRouter, prefix="", tags=["数据字段"], include_in_schema=True)
app.include_router(sysObjectsRouter, prefix="", tags=["数据对象"], include_in_schema=True)

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

# 2. 强制下载
@app.get("/d/{name}")
def down(name: str):
    p = os.path.join("static", name)
    if not os.path.isfile(p):
        return {"detail": "not found"}, 404
    return FileResponse(p, filename=name, content_disposition_type="attachment")

@app.get("/p/{name:path}")               # 支持子目录
def down(name: str):
    p = os.path.join("static", name)
    if not os.path.isfile(p):
        return {"detail": "not found"}, 404

    # 取 MIME 类型
    mime, _ = mimetypes.guess_type(p)
    if mime == "text/html":
        # 直接返回 HTML 内容，浏览器会渲染
        with open(p, "rb") as f:
            return HTMLResponse(content=f.read().decode("utf-8"))
    # 其它文件继续走下载
    return FileResponse(p, filename=os.path.basename(name),
                        content_disposition_type="attachment")

@app.get("/view/{name:path}")
def view(name: str):
    p = os.path.join("static", name)
    if not os.path.isfile(p):
        return {"detail": "not found"}, 404
    if not name.lower().endswith(".html"):
        return {"detail": "only .html allowed"}, 400
    with open(p, "rb") as f:
        return HTMLResponse(content=f.read().decode("utf-8"))

@app.post("/login")
async def regLogin(login_data: login_manager.LoginRequest,
                   db: Session = Depends(get_db),
                   app_manager: Optional[dict] = Depends(dependencies.auth_api_key)):
    retMes = login.login(db, login_data, app_manager)
    # print(login.loginInfo.get())

    return retMes  # {"access_token": login_data, "app_id": app_id}

@app.get("/menu")
async def menus_tree(username: str = Query(...), # Query(None),   # 允许空，Query(...)属于必输
                    db: Session = Depends(get_db),
                    auth: AuthManager = Depends(dependencies.auth_token)
):

    return permission.menu_tree(username,db, auth)



@app.get("/permission")
async def permission_tree(username: str = Query(...), # Query(None),   # 允许空，Query(...)属于必输
                    db: Session = Depends(get_db),
                    auth: AuthManager = Depends(dependencies.auth_token)
):

    return permission.permission_tree(username,db, auth)

@app.get("/fields", summary="根据别名查询对象头", response_model=request_model.ResponseModel)
def read_fields(
        alias=Query(..., description="对象别名，多个用逗号分隔，如 asaa,bb,ee"),
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return serverObjects.get_fields(alias, db, auth)

@app.get("/dict_tree")
async def dicts_tree(db: Session = Depends(get_db),
                    auth: AuthManager = Depends(dependencies.auth_token)
):
    return serverDicts.dict_tree(db, auth)

@app.get("/dict")
async def dict_list(id: Optional[str] = Query(None, description="主键"),
                    dict_code: Optional[str] = Query(None, description="字典编码"),
                    db: Session = Depends(get_db),
                    auth: AuthManager = Depends(dependencies.auth_token)
):
    return serverDicts.dict_list(db, auth,id=id,dict_code=dict_code)

@app.post("/changepwd", response_model=request_model.ResponseModel)
async def changePassword(change_password: login_manager.ChangePasswordRequest,
                         db: Session = Depends(get_db),
                         auth: AuthManager = Depends(dependencies.auth_token)):
    retMes = login.changePassword(db,
                                  auth,
                                  change_password)

    return retMes


@app.post("/refreshpwd", response_model=request_model.ResponseModel)
async def refreshPassword(reset_password: login_manager.RefreshPasswordRequest,
                          db: Session = Depends(get_db),
                          auth: AuthManager = Depends(dependencies.auth_token)):
    retMes = login.refreshPassword(db,
                                   auth,
                                   reset_password)
    return retMes


# 使用依赖项
@app.get("/items")
async def read_items(auth: AuthManager = Depends(dependencies.auth_token)):
    return auth


@app.get("/headers")
async def get_headers(request: Request):
    headers = request.headers
    return {"headers": dict(headers)}

# 创建用户
